package org.xyz.util;

import android.annotation.TargetApi;
import android.hardware.Camera;
import android.os.Build;

/**
 * 摄像头工具类
 * @author dai.rui.lin
 *
 */
public class CameraHelper {
	
	/**
	 * 创建 Camera实例
	 * @return
	 */
	public static Camera getCameraInstance() {
		Camera c = null;
		try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
				int CammeraIndex = FindBackCamera();
				if (CammeraIndex == -1) {
					CammeraIndex = FindFrontCamera();
				}
				c = Camera.open(CammeraIndex);
				return c;
			}
			c = Camera.open();
			return c;
		} catch (Exception e) {
			e.printStackTrace();
			return c;
		}
		
	}
	
	@TargetApi(9)
	private static int FindBackCamera() {
		int cameraCount = 0;
		Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
		cameraCount = Camera.getNumberOfCameras(); // get cameras number

		for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
			Camera.getCameraInfo(camIdx, cameraInfo); // get camerainfo
			if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
				// 代表摄像头的方位，目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
				return camIdx;
			}
		}
		return -1;
	}

	@TargetApi(9)
	private static int FindFrontCamera() {
		int cameraCount = 0;
		Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
		cameraCount = Camera.getNumberOfCameras(); // get cameras number

		for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
			Camera.getCameraInfo(camIdx, cameraInfo); // get camerainfo
			if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT
					) {
				// 代表摄像头的方位，目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
				return camIdx;
			}
		}
		return -1;
	}

}
